import { ipcMain } from "electron";
import "./shell.ts";
import "./fs.ts";
import "./cp.ts";
import "./http.ts";
import "./archives.ts";
import "./config-file.ts";

(() => {
  /*
   * 通过IPC直接传入模块名、对象名、方法名，调用对应的方法
   */

  const invokeNode = async (api: string, args: any[]) => {
    // api: <moduleName>[.objectName][.funcName]
    const [moduleName, ...props] = api.split(".");

    // console.log(moduleName, props);
    let caller = await import(moduleName);
    const funcName = props[props.length - 1];
    for (let i = 0; i < props.length - 1; i++) {
      const prop = props[i];
      caller = caller[prop];
    }

    return funcName
      ? typeof caller[funcName] === "function"
        ? caller[funcName](...args) // 调用函数
        : caller[funcName] // 获取属性
      : caller(...args);
  };

  ipcMain.handle("__invoke_node__", (_, api: string, ...args: any[]) => invokeNode(api, args));

  // 传入一连串模块函数名称和方法参数, 依次调用
  // 如果前面的方法返回值不为空, 则作为参数传入下一个方法
  // [
  //    [api, args[]],
  //    [api, args[]],
  // ]
  ipcMain.handle("__invoke_node_chain__", async (_, args: [string, any[] | undefined][]) => {
    let lastReturn: any = undefined;
    // console.log('__invoke_node_chain__', args);
    for (const it of args) {
      const [api, invokeArgs = []] = it;
      const params = lastReturn == null ? invokeArgs : [lastReturn, ...invokeArgs];
      // console.log("invokeNode", it, api, params);

      lastReturn = await invokeNode(api, params);
    }
    return lastReturn;
  });
})();
